package com.lhkj.ct.base.json;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;

import java.io.IOException;
import java.util.Objects;

public class SensitiveSerializer extends JsonSerializer<String> implements ContextualSerializer {

   private SensitiveEnum sensitiveEnum;

   @Override
   public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property) throws JsonMappingException {
       SensitiveData annotation = property.getAnnotation(SensitiveData.class);
       if (Objects.nonNull(annotation) && Objects.equals(String.class, property.getType().getRawClass())) {
           this.sensitiveEnum = annotation.strategy();
           return this;
       }
       return prov.findValueSerializer(property.getType(), property);
   }

    @Override
    public void serialize(String value, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        jsonGenerator.writeString(sensitiveEnum.desensitizer().apply(value));
    }

}

